package servlet;

import com.mysql.jdbc.PreparedStatement;
import model.Commodity;
import util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/UploadCommodityServlet.do")
public class UploadCommodityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.setCharacterEncoding("utf-8");
//        int CID = Integer.parseInt(request.getParameter("cid"));
        String C_NAME = request.getParameter("c_name");
        int NUMBER = Integer.parseInt(request.getParameter("number"));
        float PRICE = Float.parseFloat(request.getParameter("price"));
//        String PHOTO = "images/水果/"+request.getParameter("photo");
        String PHOTO = request.getParameter("photo");
        if (PHOTO.equals("")){
            PHOTO+="images/未上传图片.jpg";
        }else {
//            PHOTO="images/水果/"+PHOTO;
            PHOTO="images/"+PHOTO;

        }
        // 一段sql语句

        Connection conn = null;
        List<Commodity> commodities = new ArrayList<>();
        try { // 创建PreparedStatement
            conn = DBHelper.getConnection();
            String sql = "insert into commodity(c_name, number, price, photo)values( ?, ?, ?, ?)";
            PreparedStatement pstat = (PreparedStatement) conn.prepareStatement(sql);
            // PreparedStatement赋值
            pstat.setString(1, C_NAME);
            pstat.setInt(2, NUMBER);
            pstat.setFloat(3, PRICE);
            pstat.setString(4, PHOTO);
            // 执行
            pstat.execute();
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.sendRedirect("adminCommodity.do");
    }
}
